package com.fast.develop.meta.base.resource;

import cn.hutool.core.lang.Assert;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

/**
 * @author 莫寅
 * @createTime 2022-06-24 17:52
 * @desc：
 */
public class FileResource implements Resource{


    private final String path;

    private final File file;

    private final Path filePath;


    public FileResource(String path) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.file = new File(path);
        this.filePath = this.file.toPath();
    }

    public FileResource(File file) {
        Assert.notNull(file, "File must not be null");
        this.path = file.getPath();
        this.file = file;
        this.filePath = file.toPath();
    }

    public FileResource(Path filePath) {
        Assert.notNull(filePath, "Path must not be null");
        this.path = filePath.toString();
        this.file = null;
        this.filePath = filePath;
    }


    @Override
    public InputStream getInputStream() throws IOException {
        try {
            return Files.newInputStream(this.filePath);
        }
        catch (NoSuchFileException ex) {
            throw new FileNotFoundException(ex.getMessage());
        }
    }

    public String getPath() {
        return path;
    }

    public File getFile() {
        return file;
    }

    public Path getFilePath() {
        return filePath;
    }
}
